﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using CWCS.Common.Log;
using CWCS.Core.Library;
using CWCS.Core.Library.SocketManager;

namespace COMResolution
{
    public class CRLSRMControl
    {
        public delegate void AnalyseMessageEventHandler(string CommandType, object msg);//B1声明Anysisdata 解析收到数据时事件的代理，传给BLL层
        public event AnalyseMessageEventHandler AnalyseMessageEvent;

        public static byte[] MessageHeader_2000 = new byte[] { 0x53, 0x35, 0x10, 0x01, 0x03, 0x03, 0x03, 0x08, 0x01, 0x3C, 0x00, 0x00, 0x00, 0x1A, 0xFF, 0x02 };
        public static byte[] MessageHeader_4000 = new byte[] { 0x53, 0x35, 0x10, 0x01, 0x03, 0x05, 0x03, 0x08, 0x01, 0x3D, 0x00, 0x00, 0x00, 0x12, 0xFF, 0x02 };
        public static byte[] MessageHeader_6000 = new byte[] { 0x53, 0x35, 0x10, 0x01, 0x03, 0x05, 0x03, 0x08, 0x01, 0x46, 0x00, 0x00, 0x00, 0x47, 0xFF, 0x02 };

        private SRMSocketClient OSrmSocket = new SRMSocketClient();
        private Timer CheckTimer = null;
        private Timer GetStatusTimer = null;
        private string m_serverIP, m_strSRMNo, m_MessageRecv;//堆垛机IP，字段名
        private int m_serverPort;
        private LogHelper log;

        public CRLSRMControl(string strsrmno, string ipaddress, int port)//构造函数 
        {
            m_serverIP = ipaddress;
            m_serverPort = port;
            m_strSRMNo = strsrmno;
            log = new LogHelper("Base");
            try
            {
                //订阅一个Socket收到数据的事件
                OSrmSocket.Notify += new SRMNotifyCommandHander(OSrmSocket_Notify);// 
            }
            catch (Exception ex)
            {
                log.Info(m_strSRMNo + ": SRM_Notify初始化函数异常" + ex.Message);
            }
        }
        public bool IsConnected()
        {
            return OSrmSocket.Connected;
        }
        //建立Socket连接
        public bool Startup()
        {
            try
            {
                return OSrmSocket.Connect(m_serverIP, m_serverPort);
            }
            catch (Exception ex)
            {
                log.Info(m_strSRMNo + ": CRL CRLSRMControl Connection Error!" + ex.Message);
                return false;
            }
        }
        //发送报文
        public bool SendMsg(byte[] msg)
        {
            return OSrmSocket.Send(msg);
        }

        private void OSrmSocket_Notify(string Command, object state)//信息处理
        {
            if (AnalyseMessageEvent != null)
            {
                string strmsg = "";
                if (Command == "RecvData")
                {
                    byte[] byt = (byte[])state;
                    if (m_serverPort == 6000)
                    {
                        for (int j = 0; j < 100; j++)
                        {
                            if (byt[j].ToString() != "0")
                                strmsg += j + ":" + byt[j].ToString() + ";";
                        }
                        if (!System.String.IsNullOrEmpty(strmsg))
                            log.Info(strmsg);
                    }
                    else
                    {
                        for (int i = 0; i < 74; i++)
                        {
                            strmsg += byt[i].ToString() + ";";
                        }
                        if (m_strSRMNo != "HC001" && m_serverPort == 4000 && Command == "RecvData" && byt[22].ToString() != "0")
                        {
                            if (m_MessageRecv != "任务号:" + byt[20].ToString() + "," + byt[21].ToString() + "; 低位指令代码:" + byt[22].ToString() + "; 高位指令代码:" + byt[38].ToString()
                                + "; 函数模式:" + byt[23].ToString() + "; 堆垛机模式:" + byt[38].ToString() + "; 动作点:" + byt[26].ToString() + "; 巷道:" + byt[27].ToString() + "; 行:" + byt[28].ToString()
                                + "; 列:" + byt[29].ToString() + "; 列前后:" + byt[30].ToString() + "; 高度:" + byt[31].ToString() + "; 深度:" + byt[32].ToString())
                            {
                                m_MessageRecv = "任务号:" + byt[20].ToString() + "," + byt[21].ToString() + "; 低位指令代码:" + byt[22].ToString() + "; 高位指令代码:" + byt[38].ToString()
                                + "; 函数模式:" + byt[23].ToString() + "; 堆垛机模式:" + byt[38].ToString() + "; 动作点:" + byt[26].ToString() + "; 巷道:" + byt[27].ToString() + "; 行:" + byt[28].ToString()
                                + "; 列:" + byt[29].ToString() + "; 列前后:" + byt[30].ToString() + "; 高度:" + byt[31].ToString() + "; 深度:" + byt[32].ToString() + ";监测值" + byt[7].ToString();
                                //log.WriteLog(m_MessageRecv);
                            }
                        }
                    }
                }
                else if (Command == "Break" || Command == "Connect")
                    log.Info(Command + ": " + state.ToString());
                AnalyseMessageEvent(Command, strmsg);
            }
        }

        public bool SendCode(string num, int type, int taskno, string station, bool isMan)
        {
            try
            {
                station = station.Trim('S');
                byte[] msg = new byte[24];
                int taskno1 = taskno / 256;//123
                int taskno2 = taskno % 256;//214
                int actionpoint = 1;
                int aisle1 = 1;
                msg[0] = 0x01;
                msg[1] = 0x01;//messagecount
                msg[2] = 0x00;
                msg[3] = 0x00;
                msg[4] = (byte)taskno1;
                msg[5] = (byte)taskno2;
                msg[6] = (byte)type;//GETC: 112   PUTC: 128   NOFUNC: 0
                msg[7] = 0x01;
                msg[8] = 0x00;
                msg[9] = 0x01;
                aisle1 = int.Parse(num.Substring(2, 2));//crc001

                if (station != null && station.Length == 4)
                {   //IC入库站台和，OC出库动作端的定义  输送机地址编号
                    #region
                    //出库端出入库站台编号
                    if (int.Parse(station) == 1126 || int.Parse(station) == 1119 || int.Parse(station) == 1111 || int.Parse(station) == 1104 || int.Parse(station) == 1097 || int.Parse(station) == 1089 || int.Parse(station) == 1083 || int.Parse(station) == 1075 || int.Parse(station) == 1068 || int.Parse(station) == 1061 || int.Parse(station) == 1054 || int.Parse(station) == 1046 || int.Parse(station) == 1040 || int.Parse(station) == 1032)//IC01
                    {
                        actionpoint = 2; //一楼左边站台
                    }
                    //入库端出入库站台编号
                    if (int.Parse(station) == 1123 || int.Parse(station) == 1115 || int.Parse(station) == 1106 || int.Parse(station) == 1099 || int.Parse(station) == 1092 || int.Parse(station) == 1086 || int.Parse(station) == 1078 || int.Parse(station) == 1072 || int.Parse(station) == 1063 || int.Parse(station) == 1056 || int.Parse(station) == 1049 || int.Parse(station) == 1043 || int.Parse(station) == 1035 || int.Parse(station) == 1029)//OC01
                    {
                        actionpoint = 3;//一楼右边站台
                    }
                    if (int.Parse(station) == 2175 || int.Parse(station) == 2005 || int.Parse(station) == 2012 || int.Parse(station) == 2020 || int.Parse(station) == 2027 || int.Parse(station) == 2033 || int.Parse(station) == 2042 || int.Parse(station) == 2049 || int.Parse(station) == 2055 || int.Parse(station) == 2062 || int.Parse(station) == 2070 || int.Parse(station) == 2077)//IC02
                    {
                        actionpoint = 4;
                    }
                    if (int.Parse(station) == 2001 || int.Parse(station) == 2010 || int.Parse(station) == 2017 || int.Parse(station) == 2023 || int.Parse(station) == 2030 || int.Parse(station) == 2038 || int.Parse(station) == 2045 || int.Parse(station) == 2052 || int.Parse(station) == 2060 || int.Parse(station) == 2067 || int.Parse(station) == 2073 || int.Parse(station) == 2080)//OC01
                    {
                        actionpoint = 5;
                    }
                    //3楼出入库站台
                    if (int.Parse(station) == 3003 || int.Parse(station) == 3004 || int.Parse(station) == 3005 || int.Parse(station) == 3006 || int.Parse(station) == 3007 || int.Parse(station) == 3008 || int.Parse(station) == 3009 || int.Parse(station) == 3010 || int.Parse(station) == 3011 || int.Parse(station) == 3012 || int.Parse(station) == 3013 || int.Parse(station) == 3014)//OC02
                    {
                        actionpoint = 6;
                    }
                    #endregion
                    for (int i = 10; i < 24; i++)
                        msg[i] = 0x00;
                }
                else
                {
                    if (type == 0 && string.IsNullOrEmpty(station))
                        for (int i = 12; i < 24; i++)
                            msg[i] = 0x00;
                    else
                    {
                        // msg[11] = (byte)(int.Parse(station.Substring(1, 2)));
                        //0010040031
                        // 0050140041
                        byte b = 1; //
                        int yi = int.Parse(station.Substring(2, 2));
                        msg[12] = (byte)(2 - int.Parse(station.Substring(1, 2)) % 2); // RACK SIDE 1,left;2,right   根据排来判断左右
                        if (station.Substring(1, 2) == "01" || station.Substring(1, 2) == "02" || station.Substring(1, 2) == "03" || station.Substring(1, 2) == "04")
                        {
                            msg[13] = (byte)(int.Parse(station.Substring(4, 2)));
                            msg[14] = b;
                        }
                        else
                        {
                            msg[13] = (byte)((int.Parse(station.Substring(4, 2))) / 2 + 1); //列
                            if (station.Substring(4, 2) == "01")
                                msg[14] = b;
                            else
                                msg[14] = (byte)((int.Parse(station.Substring(4, 2))) % 2 + 1);
                        }
                        msg[15] = (byte)(int.Parse(station.Substring(7, 2)));//层,1-24
                        msg[16] = (byte)(int.Parse(station.Substring(9, 1)));
                        for (int i = 17; i < 24; i++)
                            msg[i] = 0x00;
                    }
                }
                msg[10] = (byte)actionpoint;
                msg[11] = (byte)aisle1;//巷道
                msg[21] = 0x01;//0x01:100%  0x02:75% 0x03:50%
                bool sendflag = SendMsg(msg);
                if (sendflag)
                {
                    log.Info(num + " SendCode发送指令成功1:" + type.ToString() + "/" + taskno.ToString() + "/" + station);
                    AnalyseMessageEvent("SendData", string.Format("{0}下发{1}任务:{2},指令:{3},地址:{4}", isMan ? "手动" : "WCS自动", num, taskno, type, station));
                }
                else
                {
                    // 发送失败基本是掉线或者对象为空导致，重新连接一次，然后在发送一次
                    // Startup();
                    sendflag = SendMsg(msg);
                }
                if (!sendflag)
                {

                    AnalyseMessageEvent("Break", string.Format("{0},Ip:{1},Port:{2} 指令下发失败！", m_strSRMNo, m_serverIP, m_serverPort));
                    log.Info(num + " SendCode发送指令失败:" + type.ToString() + "/" + taskno.ToString() + "/" + station);
                }

                return sendflag;
            }
            catch (Exception ee)
            {
                log.Info(num + " SendCode发送指令异常:" + type.ToString() + "/" + taskno.ToString() + "/" + station + "  " + ee.Message);
                return false;
            }
        }
    }
}
